package org.william.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.william.shiro.entity.SysUser;

@Controller
public class IndexController {

    @GetMapping({"", "index"})
    public String index(Model map){
        map.addAttribute("title", "Hello Shiro!");
        return "index";
    }

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @GetMapping("/user/add")
    public String add(){
        return "/user/add";
    }

    @GetMapping("/user/edit")
    public String edit(){
        return "/user/edit";
    }

    @GetMapping("/toLogin")
    public String login(SysUser sysUser,Model map){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUsername(), sysUser.getPassword());
        try {
            subject.login(token);
            return "index";
        }catch (UnknownAccountException e){
            map.addAttribute("msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            map.addAttribute("msg","密码错误");
            return "login";
        }

    }

    @GetMapping("unauth")
    @ResponseBody
    public String unauthorized(){
        return "未授权请授权！";
    }
}
